<?php
// 引入 工具
require_once("DButil.php");

// Dao: Data Access Object
// 添加商品
function insertProduct($name,$info,$price,$unit,$imageUrl) {
    $sql = "insert into t_product (p_name,p_info,p_price,p_unit,p_image_url) "
    ." values ('$name','$info',$price,'$unit','$imageUrl') ";
    $result = update(getConn(), $sql);
    return $result;
}
// 根据 商品名称 查询
function selectByProductName($name) {
    $sql = "select p_id,p_name from t_product where p_name = '$name'";
    $result = queryOne(getConn(), $sql);
    return $result;
}
// 根据id删除商品
function deleteById($id){
    $sql = "delete from t_product where p_id = '$id'";
    return update(getConn(), $sql);
}
// 修改前的查询(根据id查询)
function selectById($id) {
    $sql = "select p_id,p_name,p_info,p_price,p_unit,p_image_url from t_product where p_id = '$id'";
    $result = queryOne(getConn(), $sql);
    return $result;
}
/**
 * 查询所有商品(分页), 需要返回 当前页的数据, 以及 总页数
 */
function selectByPage($pageNum, $pageSize) {
    $conn = getConn();
    // 查询数据总量
    $sql = "select count(1) total from t_product";
    $result = queryOne($conn, $sql);
    $total = $result["data"]["total"];
    // 计算总页数
    $pages = ceil($total/$pageSize);
    
    $data = [];
    if($total > 0){
        $m = ($pageNum - 1) * $pageSize;
        $n = $pageSize;
        // 查询当前页的数据
        $sql = "select p_id,p_name,p_info,p_price,p_unit,p_image_url from t_product limit $m, $n";
        $result = query($conn, $sql);
        $data = $result["data"];
    }
    return [
        "total" => $total,
        "pageSize" => $pageSize,
        "pages" => $pages,
        "pageNum" => $pageNum,
        "data" => $data
    ];
}
// 修改商品
function updateProduct($id,$name,$info,$price,$unit,$imageUrl) {
    $sql = "update t_product set "
    . " p_name = '$name', "
    . " p_info = '$info', "
    . " p_price = '$price', "
    . " p_unit = '$unit' ";
    if(!empty($imageUrl)){
        $sql .= " , p_image_url = '$imageUrl' ";
    }
    $sql .= " where p_id = '$id' ";
    $result = update(getConn(), $sql);
    return $result;
}

/**
 * 根据登录名和密码查询
 */
function selectNameAndPwd($name, $pwd) {
    $sql = "select su_id, su_name, su_nickname, su_pwd from t_sys_user " 
    . " where su_name = '$name' and su_pwd = '$pwd'";
    return queryOne(getConn(), $sql);
}
?>